package com.example.shiroplusdemo.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.SecureRandom;

/**
 * @author ：Anitaxiaofeng
 * @description：DES加密解密
 * @create 2018-01-07
 **/
public class MyDES {

    /**
     * DES算法密钥
     */
    private static final byte[] DES_KEY = {21,1,-110,82,-32,-85,-128,-65};

    /**
     * 数据加密(DES算法)
     * @param data
     * @return 加密后数据
     */
    public static String encryptBasedDes(String data){
        String encryptedData = null;
        try{
            SecureRandom sr = new SecureRandom(); //可靠随机数源
            DESKeySpec deskey = new DESKeySpec(DES_KEY);
            //创建一个密钥工厂，然后用它把DESKeySpec转换成一个SecretKey对象
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey key = keyFactory.generateSecret(deskey);
            //加密对象
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE,key,sr);
            //加密，并把字节数组编码成字符串
            encryptedData = new BASE64Encoder().encode(cipher.doFinal(data.getBytes()));
        }catch(Exception e){
            throw new RuntimeException("加密错误，错误信息：",e);
        }
        return encryptedData;
    }

    /**
     * 数据解密(DES算法)
     * @param cryptData
     * @return
     */
    public static String decryptBasedDes(String cryptData){
        String decryptedData = null;
        try{
            SecureRandom sr = new SecureRandom();
            DESKeySpec deskey = new DESKeySpec(DES_KEY);
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey key = keyFactory.generateSecret(deskey);
            //解密对象
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE,key,sr);
            //把字符串解码为字节数组，并解密
            decryptedData = new String(cipher.doFinal(new BASE64Decoder().decodeBuffer(cryptData)));
        }catch(Exception e){
            throw new RuntimeException("解密错误，错误信息",e);
        }
        return decryptedData;
    }

}
